<?php

namespace Shen\Rocketmq5\Service;

use Hyperf\Di\Annotation\AnnotationCollector;
use Shen\Rocketmq5\Annotation\RocketMq;

class ConfigService
{
    public function getConfig($payload): array
    {
        $isRun = [];
        if (is_array($payload) && isset($payload['name'])) {
            if (is_array($payload['name'])) {
                foreach ($payload['name'] as $value) {
                    if (is_string($value)) {
                        $isRun[] = $value;
                    }
                }
            }
        }

        $allNeedleRun = [];

        $annotations = AnnotationCollector::getMethodsByAnnotation(RocketMq::class);

        $needleRun = [];
        $needleClose = [];
        if (!empty($annotations)) {
            foreach ($annotations as $data) {
                $annotation = $data['annotation'];
                $name = $data['class'] . "::" . $data['method'];
                if (isset($annotation->enable)) {

                    if ($annotation->enable) {
                        $allNeedleRun[] = $name;
                        if (!in_array($name, $isRun) && !empty($annotation->topic) && !empty($annotation->group)) {
                            $needleRun[] = [
                                'class' => $data['class'],
                                'method' => $data['method'],
                                'topic' => $annotation->topic,
                                'group' => $annotation->group,
                                'num' => max($annotation->num, 1),
                                'invisible_durations' => $annotation->invisibleDurations,
                                'mode_type' => $annotation->modeType,
                                'mode' => $annotation->mode,
                            ];
                        }
                    } else {
                        if (in_array($name, $isRun)) {
                            $needleClose[] = $name;
                        }
                    }

                }
            }
        }

        $needleClose = array_merge($needleClose, array_diff($isRun, $allNeedleRun));

        return [
            "needle_run" => $needleRun,
            "needle_close" => $needleClose,
            "result" => true,
        ];
    }
}